package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.AgeDomain;
import server.AlexaUpdate;
import server.GetPage;
import server.GooglePageRank;
import server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;
import data.Memcache;

@SuppressWarnings("serial")
public class WhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = Utils.fomatDomain(st.nextToken());
		if(Utils.checkDomain(name))
		{
			DBCollection coll = Data.data("domain");
	
			DBObject domains = coll.findOne(new BasicDBObject("name",name));
			
			if(domains != null)
			{
				@SuppressWarnings({ "unchecked"})
				ArrayList<String> lastPing = (ArrayList<String>)Utils.cache.get("last-whois");
	        	
	        	
	        	if(lastPing != null && lastPing.size() > 0)
	        	{
		        	if(lastPing.size()>19)
		        	{
		        		lastPing.remove(0);
		        	}
		        	int check = 0;
		        	for (int i = 0; i < lastPing.size(); i++) {
						if(lastPing.get(i).equals(name))
						{
							check = 1;
						}
					}
		        	if(check == 0)
		        		lastPing.add(name);
		        		Utils.cache.put("last-whois", lastPing);
	        	} else {
	        		ArrayList<String> lastPings =  new ArrayList<String>();
	        		lastPings.add(name);
	        		Utils.cache.put("last-whois", lastPings);
	        	}
				
				req.setAttribute("domain", domains);
				req.setAttribute("name", name);
				try {
					req.getRequestDispatcher("/whois.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				Random generator = new Random();
				int r = generator.nextInt(100000);
				DBObject domain = new BasicDBObject();
				domain.put("name", name);
				domain.put("update", new Date().getTime());
				domain.put("random", r);

				try {
					new GetPage(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GooglePageRank(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AgeDomain(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AlexaUpdate(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new Whois(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					Thread.sleep(5000);
					coll.save(domain);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Memcache.setMemcache("last-update", domain.get("name").toString());
				
				resp.sendRedirect("/whois/"+name);
			}
		} else {
			resp.getWriter().println("domain does not exist !");
		}
	}

}
